<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
    <% String path=request.getContextPath(); String basePath=request.getScheme() + "://" + request.getServerName() + ":"
        + request.getServerPort() + path + "/" ; %>

        <!DOCTYPE html>
        <html>

        <head>
            <base href="<%=basePath%>">

            <title></title>

            <meta http-equiv="pragma" content="no-cache">
            <meta http-equiv="cache-control" content="no-cache">
            <meta http-equiv="expires" content="0">
            <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
            <meta http-equiv="description" content="This is my page">
            <!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

        </head>

        <body>
            <%@ include file="/WEB-INF/jsp/common/header.jsp" %>
                <%@ include file="/WEB-INF/jsp/common/loadDiv.jsp" %>
                    <script type="text/javascript">
                        $(function () {
                            $('#startTime').datebox('setValue', getBeforeCurrentDate30Days());
                            $('#endTime').datebox('setValue', getNowFormatDate());
                            $('#startDeliveryTime').datebox('setValue', getBeforeCurrentDate30Days());
                            $('#endDeliveryTime').datebox('setValue', getNowFormatDate());
                            bindgrid();
                            // 初始化选择交货单的datagrid
                            setDeliveryDataGrid();
                            // 初始化待选供应商选择列表
                            setSuppliesDatagird()
                        });


                    </script>

                    <style scoped="scoped">
                        .textbox {
                            height: 20px;
                            margin: 0;
                            padding: 0 2px;
                            box-sizing: content-box;
                        }

                        /*.table tr {
height: 15px;
}*/
                    </style>
                    <div class="query_criteria" id="query_criteria">
                        <div style="margin: 5px 0px">
                            <%-- 搜索框 --%>
                                <label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox"
                                    name="startTime" id="startTime"
                                    data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                    value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
                                    class="easyui-datebox" name="endTime" id="endTime"
                                    data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                    style="width: 150px" /> <label
                                    style="margin-left: 20px; font-size: 12px;">状态：</label>
                                <input class="easyui-combobox" id="search_status" name="search_status"
                                    style="width: 80px;" data-options="valueField: 'value',editable:false,
						textField: 'label',panelHeight:'auto',data: [{
							label: '全部',
							value: ''
						},{
							label: '待提交',
							value: '0',
							selected:true
						},{
							label: '已提交',
							value: '1'
						}]">
                                </select> <a id="search" style="margin-left: 30px" href="javascript:void(0)"
                                    class="easyui-linkbutton" data-options="iconCls:'icon-search'"
                                    onclick="selectList()">查询</a> <a id="export" href="javascript:void(0)"
                                    class="easyui-linkbutton" data-options="iconCls:'icon-export'"
                                    onclick="exportList()">导出</a>
                        </div>

                        <table id="dg"></table>

                        <div id="add" class="easyui-window" closed="true" modal="true" title="详细信息"
                            style="width: 930px; height: 400px; padding: 5px 5px; top: 50px;">
                            <div id="tabs" class="easyui-tabs" style="width: 885px; height: 350px">
                                <div title="基本信息" style="padding: 5px;">
                                    <form id="fm" class="ssec-form">
                                        <table class="table">
                                            <tr>
                                                <input id="purId" name="purId" type="hidden"
                                                    data-options="required:false" />

                                                <td>
                                                    <div class="ssec-label">SAP采购订单号：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="sapOrderNo" name="sapOrderNo" class="easyui-textbox"
                                                            data-options="required:false,editable:false" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">标题：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="title" name="title" class="easyui-textbox"
                                                            data-options="required:true,editable:true" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">采购组织：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="purchaseOrg" name="purchaseOrg"
                                                            class="easyui-textbox"
                                                            data-options="required:false,editable:false" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">公司代码：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="companyCode" name="companyCode"
                                                            class="easyui-textbox"
                                                            data-options="required:false,editable:false" />
                                                    </div>
                                                </td>

                                                <td>
                                                    <div class="ssec-label">采购组：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="purchaseGroup" name="purchaseGroup"
                                                            class="easyui-textbox"
                                                            data-options="required:false,editable:false" />
                                                    </div>
                                                </td>

                                                <td>
                                                    <div class="ssec-label">供应商编码：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal" onclick="showBrokerageSupplies()">
                                                        <input id="supplyCode" name="supplyCode" class="easyui-textbox"
                                                            data-options="required:true,editable:false,prompt:'点击选择供应商信息'" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">供应商名称：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="supplyName" name="supplyName" class="easyui-textbox"
                                                            data-options="required:false,editable:false" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">付款方式：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="paymentType" name="paymentType"
                                                            class="easyui-combobox"
                                                            data-options="editable:false,required:true,url:'sysDict/queryItemByTypeName?dicName=付款条件',method:'get',
					                                                         valueField:'dicValue',textField:'dicName',panelHeight:'auto'" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">约定货币：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="curreny" name="curreny" class="easyui-combobox"
                                                            data-options="editable:false,required:true,url:'sysDict/queryItemByTypeName?dicName=货币',method:'get',
					                                                         valueField:'dicValue',textField:'dicName',panelHeight:'auto',onSelect:function(record){
					                                                         // 选择项的触发事件
					                                                         setExchangeRate(record)
					                                                         }" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">费用类型：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="costType" name="costType" class="easyui-combobox"
                                                            data-options="editable:false,required:true,url:'sysDict/queryItemByTypeName?dicName=六大费用名称',method:'get',
					                                                         valueField:'dicValue',textField:'dicName',panelHeight:'auto'" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">税码：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="taxCode" name="taxCode" class="easyui-combobox"
                                                            data-options="editable:false,required:true,url:'sysDict/queryItemByTypeName?dicName=税码',method:'get',
					                                                         valueField:'dicValue',textField:'dicName',panelHeight:'auto'" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">工厂代码：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="factoryCode" name="factoryCode"
                                                            class="easyui-combobox"
                                                            data-options="editable:false,required:true,url:'sysDict/queryItemByTypeName?dicName=交货工厂',method:'get',
					                                                         valueField:'dicValue',textField:'dicName',panelHeight:'auto'" />
                                                    </div>
                                                </td>

                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">费用物料组：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="costMmGroupCode" name="costMmGroupCode"
                                                            class="easyui-combobox"
                                                            data-options="editable:false,required:true,url:'sysDict/queryItemByTypeName?dicName=六大费用物料组描述',method:'get',
					                                                         valueField:'dicValue',textField:'dicName',panelHeight:'auto'" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">付款货币：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="payCurreny" name="payCurreny" class="easyui-combobox"
                                                            data-options="editable:false,required:true,url:'sysDict/queryItemByTypeName?dicName=货币',method:'get',
					                                                         valueField:'dicValue',textField:'dicName',panelHeight:'auto',
					                                                         onSelect:function(record){
					                                                         // 选择项的触发事件
					                                                         setPayCurrenyExchangeRate(record)
					                                                         },
					                                                         // 下拉面板显示的时候触发
					                                                         onShowPanel:function(){
                                                                              let fCURR = $('#curreny').combobox('getValue')
                                                                              if (!fCURR) {
                                                                              $('#payCurreny').combobox('hidePanel')
                                                                                  $.messager.alert('提示','请先选择约定货币')
                                                                                  return
                                                                              }
                                                                              }" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">汇率：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="rate" name="rate" class="easyui-numberbox"
                                                            data-options="required:false,editable:true,precision:4" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">创建人姓名：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="createName" name="createName" class="easyui-textbox"
                                                            data-options="required:false,editable:false" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">创建时间：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="createTime" name="createTime" class="easyui-textbox"
                                                            data-options="required:false,editable:false" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">订单含税费用：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="orderAmountTax" name="orderAmountTax"
                                                            class="easyui-numberbox"
                                                            data-options="required:false,editable:false,precision:2" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">税额：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="taxAmount" name="taxAmount" class="easyui-numberbox"
                                                            data-options="required:false,editable:false,precision:2" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">订单不含税费用：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="orderAmountExTax" name="orderAmountExTax"
                                                            class="easyui-numberbox"
                                                            data-options="required:false,editable:false,precision:2" />
                                                    </div>
                                                </td>
                                            </tr>
                                        </table>
                                    </form>
                                </div>
                                <div title="费用列表" style="padding: 5px;display: none">
                                    <table id="costLines"></table>
                                </div>

                            </div>
                        </div>
                        <!-- 选择交货单的弹窗 -->
                        <div id="selectDeliveryWindow" class="easyui-window" closed="true" modal="true" title="交货单列表"
                            style="width: 900px; height: 400px; padding: 5px 5px">
                            <!-- 搜索框 -->
                            <label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox"
                                id="startDeliveryTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
                                class="easyui-datebox" id="endDeliveryTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                style="width: 150px" /> <a style="margin-left: 30px" href="javascript:void(0)"
                                class="easyui-linkbutton" data-options="iconCls:'icon-search'"
                                onclick="selectDeliveryList()">查询</a><a style="margin-left: 5px"
                                href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'"
                                onclick="addSapDeliverToCostLines()">确定</a>
                            <!--交货单列表DataGrid  -->
                            <table id="deliveryList"></table>
                        </div>
                        <%-- 选择供应商的弹窗 --%>
                            <div id="selectSupplyWindow" class="easyui-window" closed="true" modal="true" title="待选供应商"
                                style="width: 900px; height: 400px; padding: 5px 5px">
                                <%--待选供应商列表DataGrid --%>
                                    <table id="supplyDataGrid"></table>
                            </div>
                    </div>
        </body>
        <script>
            var editIndex = undefined;
            // tab未被选择的监听事件
            $('#tabs').tabs({
                onUnselect: function (title, index) {
                    if (endEditing()) {
                        $('#costLines').datagrid('acceptChanges');
                    }
                }

            })

            // 行编辑结束
            function endEditing() {

                if (editIndex == undefined) {
                    return true
                }
                if ($('#costLines').datagrid('validateRow', editIndex)) {
                    $('#costLines').datagrid('endEdit', editIndex);
                    editIndex = undefined;
                    return true;
                } else {
                    $.messager.alert('提示', '费用列表有未填写数据!')
                    return false;
                }
            }

            // 初始化费用采购列表
            function bindgrid() {
                var startTime = $('#startTime').datebox('getValue')
                var endTime = $('#endTime').datebox('getValue')
                var status = $('#search_status').combobox('getValue');
                $('#dg').datagrid({
                    title: '',
                    queryParams: {
                        startTime: startTime,
                        endTime: endTime,
                        status: status
                    },
                    url: "purchase/sixCosts/selectList",
                    iconCls: 'icon-application',
                    width: getWidth(0.98),
                    height: 400,
                    nowrap: true,
                    filterDelay: 0,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    clientPaging: false,
                    remoteFilter: true,
                    singleSelect: true,
                    pagination: true,
                    remoteSort: true,
                    frozenColumns: [[
                        {
                            field: 'purId',
                            title: '费用采购ID',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'sapOrderNo',
                            title: 'SAP采购订单号',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return '<a href="javascript:void(0)" onclick="editrow(' + index + ')">' + (val ? val : '') + '</a>';
                            }
                        }, {
                            field: 'title',
                            title: '标题',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        },]],
                    columns: [
                        [{
                            field: 'factoryCode',
                            title: '工厂代码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        },
                        //     {
                        //     field: 'demandType',
                        //     title: '需求类型',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return val ? unescape(val) : '';
                        //     }
                        // },
                        {
                            field: 'purchaseOrg',
                            title: '采购组织',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'companyCode',
                            title: '公司代码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'purchaseGroup',
                            title: '采购组',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'supplyCode',
                            title: '供应商编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'supplyName',
                            title: '供应商名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'paymentType',
                            title: '付款方式',
                            hidden: true,
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'tax',
                            title: '税率',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'curreny',
                            title: '币种',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'costType',
                            title: '费用类型',
                            sortable: true,
                            formatter: function (val, rec) {
                                let txt = "";
                                switch (val) {
                                    case 'YJ':
                                        txt = '佣金';
                                        break;
                                    case 'BXF':
                                        txt = '保险费';
                                        break;
                                    case 'GZF':
                                        txt = 'FOB港杂费';
                                        break;
                                    case 'JYF':
                                        txt = '查验费';
                                        break;
                                    case 'BJF':
                                        txt = '报检费（包含危包证费、通关单费、通关单换单费）';
                                        break;
                                    case 'BGF':
                                        txt = '报关费';
                                        break;
                                }
                                return val ? txt : '';
                            }
                        }, {
                            field: 'createId',
                            title: '创建人id',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'createName',
                            title: '创建人姓名',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        },
                        {
                            field: 'createTime',
                            title: '创建时间',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        },
                        //  {
                        //     field: 'updateId',
                        //     title: '更新人id',
                        //     sortable: true,
                        //     hidden: true,
                        //     formatter: function (val, rec) {
                        //         return val ? unescape(val) : '';
                        //     }
                        // }, {
                        //     field: 'updateName',
                        //     title: '更新人姓名',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return val ? unescape(val) : '';
                        //     }
                        // }, {
                        //     field: 'updateTime',
                        //     title: '更新时间',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return val ? unescape(val) : '';
                        //     }
                        // }, {
                        //     field: 'deptName',
                        //     title: '部门名称',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return val ? unescape(val) : '';
                        //     }
                        // },
                        {
                            field: 'status',
                            title: '状态',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val == '0' ? '未提交' : '已提交';
                            }
                        }, {
                            field: 'deptId',
                            title: '部门id',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }]],
                    toolbar: [{
                        text: '增加',
                        iconCls: 'icon-add',
                        handler: function () {
                            $('#dg').datagrid('clearSelections');
                            $('#fm').form('clear');
                            $('#add').window('open');
                            bindCostLinesgrid([])
                            initBtn('0');
                            $('#tabs').tabs('select', 0)
                        }
                    }, '-',
                    {
                        text: '编辑',
                        iconCls: 'icon-edit',
                        handler: function () {
                            editrow()
                        }
                    },
                        '-',
                    {
                        text: '删除',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            var row = $('#dg').datagrid('getSelected');
                            if (row) {
                                if (row.status > 0) {
                                    $.messager.alert('消息', '已提交，不可删除！');
                                    return;
                                }
                                $.messager.confirm('提示', '确定要删除本条数据吗?', function (r) {
                                    if (r) {
                                        del(row);
                                    }
                                });
                            } else {
                                $.messager.alert('消息', '请选中一条数据');
                            }
                        }
                    }],
                    onLoadSuccess: function () {
                    },
                    onDblClickRow: function () {
                        //  editrow();
                    }
                });
                $('#dg').datagrid('enableFilter');
            }

            // 按条件查询费用采购列表
            function selectList() {
                var startTime = $('#startTime').datebox('getValue')
                var endTime = $('#endTime').datebox('getValue')
                var status = $('#search_status').combobox('getValue');
                var dg = $('#dg');
                dg.datagrid('enableFilter');
                dg.datagrid('load', {
                    startTime: startTime ? startTime : '',
                    endTime: endTime ? endTime : '',
                    status: status ? status : ''
                });
            }

            // 初始化费用采购行项目
            function bindCostLinesgrid(lines) {
                let flag = true
                let costTypeTemp = $('#costType').combobox('getValue')
                if (costTypeTemp == 'YJ') {
                    flag = false
                }
                $('#costLines').datagrid({
                    title: '',
                    data: lines,
                    iconCls: 'icon-application',
                    width: 860,
                    height: 300,
                    nowrap: true,
                    filterDelay: 0,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    clientPaging: false,
                    remoteFilter: true,
                    singleSelect: true,
                    pagination: true,
                    remoteSort: true,
                    frozenColumns: [[
                        {
                            field: 'lineId',
                            title: '费用采购行项目ID',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'purId',
                            title: '费用采购ID',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'deliveryNo',
                            title: '交货单号',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'sapOrderNo',
                            title: 'SAP采购订单号',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        },]],
                    columns: [
                        [
                            {
                                field: 'factoryCode',
                                title: '工厂代码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'contractName',
                                title: '销售合同名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'contractCode',
                                title: '销售合同号',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'vkorg',
                                title: '销售组织',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            },
                            {
                                field: 'custCode',
                                title: '客户编码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            },
                            {
                                field: 'custName',
                                title: '客户名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            },
                            {
                                field: 'deliveryType',
                                title: '交货单类型',
                                sortable: true,
                                hidden: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'deliveryTypeDesc',
                                title: '交货单类型描述',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'costType',
                                title: '费用类型',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'costAmount',
                                title: '含税费用总额',
                                editor: { type: 'numberbox', options: { precision: 3, required: true } },
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '0';
                                }
                            }, {
                                field: 'costExtaxAmount',
                                title: '不含税费用总额',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '0';
                                }
                            }, {
                                field: 'costCurreny',
                                title: '费用货币',
                                sortable: true,
                                editor: {
                                    type: 'combobox',
                                    options: {
                                        url: 'sysDict/queryItemByTypeName?dicName=货币',
                                        method: 'get',
                                        mode: 'remote',
                                        valueField: "dicValue",
                                        textField: "dicName",
                                        editable: false,
                                        required: true,
                                        onSelect: function (record) {

                                        }
                                    }
                                },
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'costUnitPrice',
                                title: '费用单价',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '0';
                                }
                            }, {
                                field: 'costUnitCureny',
                                title: '费用单价货币',
                                sortable: true,
                                editor: {
                                    type: 'combobox',
                                    options: {
                                        url: 'sysDict/queryItemByTypeName?dicName=货币',
                                        method: 'get',
                                        mode: 'remote',
                                        valueField: "dicValue",
                                        textField: "dicName",
                                        editable: false,
                                        required: true,
                                        onSelect: function (record) {

                                        }
                                    }
                                },
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'costSupplyCode',
                                title: '费用供应商编码',
                                sortable: true,
                                width: 300,
                                editor: {
                                    type: 'combogrid',
                                    options: {
                                        delay: 500,
                                        url: 'supply/info/selectSupplyForCombo',
                                        method: 'post',
                                        idField: "infCode",
                                        textField: "infName",
                                        fitColumns: true,
                                        queryParams: {},
                                        columns: [[
                                            { field: 'infCode', title: '编码', width: 120, sortable: true },
                                            { field: 'infName', title: '名称', width: 400, sortable: true }
                                        ]],
                                        editable: true,
                                        required: true
                                    }
                                },
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'costSupplyName',
                                title: '费用供应商名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'factoryCode',
                                title: '工厂代码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'materialCode',
                                title: '物料编码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'materialName',
                                title: '物料名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'signQuantity',
                                title: '签收数量',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'saleOrderNo',
                                title: '销售订单',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'saleOrderLineNo',
                                title: '销售订单行项目',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'materialGropCode',
                                title: '物料组',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }
                        ]
                    ],
                    onLoadSuccess: function () {
                    },
                    // 完成行编辑时的事件（结束当前行编辑后，开始下一行编辑前触发的）
                    onAfterEdit: function (rowIndex, rowData, changes) {
                    },
                    //
                    onEndEdit(index, row) {
                        var ed = $(this).datagrid('getEditor', {
                            index: index,
                            field: 'costSupplyCode'
                        });
                        row.costSupplyName = $(ed.target).combogrid('getText');
                    },
                    onClickCell: function (rowIndex, field, value) {
                        if (!flag) {
                            return
                        }
                        if (editIndex != rowIndex) {
                            if (endEditing()) {

                                $('#costLines').datagrid('selectRow', rowIndex)
                                    .datagrid('beginEdit', rowIndex);
                                var ed = $('#costLines').datagrid('getEditor', { index: rowIndex, field: field });
                                if (ed) {
                                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                                }
                                editIndex = rowIndex;
                            } else {
                                setTimeout(function () {
                                    $('#dg').datagrid('selectRow', editIndex);
                                }, 0);
                            }
                        }
                    }
                });
                $('#dg').datagrid('enableFilter');
            }

            // 设置待选交货单列表的dataGrid
            function setDeliveryDataGrid() {
                let startTime = $('#startDeliveryTime').datebox('getValue')
                let endTime = $('#endDeliveryTime').datebox('getValue')
                let deliveryDataGrid = $('#deliveryList');
                deliveryDataGrid.datagrid({
                    queryParams: {
                        startTime: startTime ? startTime : '',
                        endTime: endTime ? endTime : '',
                        status: '0'
                    },
                    url: 'sale/delivery/orders/selectList',
                    iconCls: 'icon-application',
                    clientPaging: false,
                    checkOnSelect: true,
                    remoteFilter: true,
                    filterDelay: 0,
                    width: 860,
                    height: 300,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20, 30, 40, 50],
                    remoteSort: true,
                    pagination: true,
                    frozenColumns: [[
                        {
                            field: 'ck',
                            checkbox: true,
                            width: 100,
                        }, {
                            field: 'deliId',
                            title: '交货单ID',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'orderNo',
                            title: '交货单编号',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        },]],
                    columns: [
                        [{
                            field: 'orderType',
                            title: '交货单类型',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'orderTypeDesc',
                            title: '交货单类型描述',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'vkorg',
                            title: '销售组织',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'customerCode',
                            title: '客户编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'customerName',
                            title: '客户名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'deliveryLineNo',
                            title: '交货行项目号',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'mmCode',
                            title: '物料编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'mmDesc',
                            title: '物料描述',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'mmGroup',
                            title: '物料组',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'mmGroupDesc',
                            title: '物料组描述',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'factoryCode',
                            title: '所属工厂',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'storage',
                            title: '存储地点',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'deliveryQuantity',
                            title: '发货数量',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'deliveryUnit',
                            title: '发货单位',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'signQuantity',
                            title: '签收数量',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'batch',
                            title: '批次',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'postDate',
                            title: '过账日期',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'deliveryStatus',
                            title: '发货状态',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'signStatus',
                            title: '签收状态',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'saleOrderNo',
                            title: '销售订单号',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'saleOrderLineNo',
                            title: '销售订单行号',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'saleContractNo',
                            title: '销售合同号',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'saleContractName',
                            title: '合同名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'brokerage',
                            title: '佣金',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'brokerageCurreny',
                            title: '佣金货币',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'brokerageUnitPrice',
                            title: '佣金单价',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'brokerageUnitPriceCurrent',
                            title: '佣金单价货币',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'brokerageSupplyCode',
                            title: '佣金供应商编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'brokerageSupplyName',
                            title: '佣金供应商名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'brokerageEnd',
                            title: '该交货单佣金业务是否已完成',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val) == '1' ? '是' : '否';
                            }
                        }, {
                            field: 'portSurcharge',
                            title: 'FOB港杂费',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'portSurchargeCurreny',
                            title: 'FOB港杂费货币',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'portSurchargeSupply',
                            title: 'FOB港杂供应商编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        },
                        {
                            field: 'portSurchargeSupplyName',
                            title: 'FOB港杂供应商名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'portSurchargeEnd',
                            title: 'FOB港杂费业务是否完成',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val) == '1' ? '是' : '否';
                            }
                        }, {
                            field: 'premium',
                            title: '保险费',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'premiumCurreny',
                            title: '保险费货币',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'premiumSupply',
                            title: '保险费供应商编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'premiumSupplyName',
                            title: '保险费供应商名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'premiumEnd',
                            title: '保险费业务是否完成',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val) == '1' ? '是' : '否';
                            }
                        }, {
                            field: 'customs',
                            title: '报关费',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'customsCurreny',
                            title: '报关费货币',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'customsSupply',
                            title: '报关费供应商编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'customsSupplyName',
                            title: '报关费供应商名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'customsEnd',
                            title: '报关费业务是否完成',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val) == '1' ? '是' : '否';
                            }
                        }, {
                            field: 'costomsCensoringCharges',
                            title: '报检费（包含危包证费、通关单费、通关单换单费）',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'costomsCensoringChargesCurreny',
                            title: '报检费（包含危包证费、通关单费、通关单换单费）货币',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'costomsCensoringChargesSupply',
                            title: '报检供应商编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'costomsCensoringChargesSupplyName',
                            title: '报检供应商名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'costomsCensoringChargesEnd',
                            title: '报检业务是否完成',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val) == '1' ? '是' : '否';
                            }
                        }, {
                            field: 'surveyFees',
                            title: '查验费',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'surveyFeesCurreny',
                            title: '查验费货币',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'surveyFeesSupply',
                            title: '查验供应商编码',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'surveyFeesSupplyName',
                            title: '查验供应商名称',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'surrveyFeesEnd',
                            title: '查验费业务是否完成',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val) == '1' ? '是' : '否';
                            }
                        }, {
                            field: 'createTime',
                            title: '创建时间',
                            sortable: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }
                        ]
                    ],
                    // toolbar: [{
                    //     text: '确定',
                    //     iconCls: 'icon-ok',
                    //     handler: function () {
                    //         addSapDeliverToCostLines(selecteds)
                    //     }
                    // }],
                    onLoadSuccess: function () {
                    },
                })
                deliveryDataGrid.datagrid('enableFilter');
            }

            // 将sap交货单追加至费用采购行项目
            function addSapDeliverToCostLines() {
                let deliveryDataGrid = $('#deliveryList');
                const selecteds = deliveryDataGrid.datagrid('getChecked')
                // 币种
                let curreny = $('#curreny').combobox('getValue')
                // 费用类型
                let costTypeTemp = $('#costType').combobox('getValue')
                // 费用类型描述
                let costTypeTextTemp = $('#costType').combobox('getText')
                // 费用物料组CODE
                let costMmGroupCode = $('#costMmGroupCode').combobox('getValue')
                let costMmGroupName = $('#costMmGroupCode').combobox('getText')
                if (!costTypeTemp) return
                // 判断费用行项目中是否已包含勾选的交货单行
                const costLinesArr = $('#costLines').datagrid('getRows')
                if (selecteds) {
                    // 判断是否是同一个工厂
                    if (!selecteds.every((item, index) => {
                        if (item.factoryCode == selecteds[0].factoryCode) {
                            return true
                        } else {
                            $.messager.alert('警告', '请选择同一工厂下的交货单')
                            return false
                        }
                    })) return

                    for (let i = 0; i < selecteds.length; i++) {
                        let o = selecteds[i]

                        let tempLine = {}
                        // 客户编码
                        tempLine.custCode = o.customerCode
                        // 客户名称
                        tempLine.custName = o.customerName
                        // 销售组织
                        tempLine.vkorg = o.vkorg
                        // 交货单号
                        tempLine.deliveryNo = o.orderNo
                        // 合同名称
                        tempLine.contractName = o.saleContractName
                        // 合同号
                        tempLine.contractCode = o.saleContractNo
                        // 交货单类型
                        tempLine.deliveryType = o.orderType
                        // 交货单类型描述
                        tempLine.deliveryTypeDesc = o.orderTypeDesc
                        // 费用类型
                        tempLine.costType = costTypeTextTemp
                        // 工厂
                        tempLine.factoryCode = o.factoryCode
                        // 费用总额
                        switch (costTypeTemp) {
                            case 'YJ':
                                if (o.brokerageEnd == '1') {
                                    $.messager.alert('提示', '交货单号' + o.orderNo + '的' + costTypeTextTemp + '已生成采购订单，请重新选择')
                                    return
                                }
                                // if (o.brokerageCurreny != curreny) {
                                //     $.messager.alert('提示', '所选交货单' + costTypeTextTemp + '币种不正确，请重新选择')
                                //     return
                                // }
                                // if (o.brokerageUnitPriceCurrent != curreny) {
                                //     $.messager.alert('提示', '所选交货单' + costTypeTextTemp + '单价币种不正确，请重新选择')
                                //     return
                                // }
                                if (o.brokerageSupplyCode && selecteds[0].brokerageSupplyCode && (o.brokerageSupplyCode != selecteds[0].brokerageSupplyCode)) {
                                    $.messager.alert('提示', '所选交货单供应商不一致，请重新选择')
                                    return
                                }
                                tempLine.costAmount = o.brokerage
                                tempLine.costCurreny = o.brokerageUnitPriceCurrent
                                tempLine.costUnitPrice = o.brokerageUnitPrice
                                tempLine.costUnitCureny = o.brokerageUnitPriceCurrent
                                tempLine.costSupplyCode = o.brokerageSupplyCode
                                tempLine.costSupplyName = o.brokerageSupplyName
                                break
                            case 'GZF':
                                if (o.portSurchargeEnd == '1') {
                                    $.messager.alert('提示', '交货单号' + o.orderNo + '的' + costTypeTextTemp + '已生成采购订单，请重新选择')
                                    return
                                }
                                // if (o.portSurchargeCurreny != curreny) {
                                //     $.messager.alert('提示', '所选交货单' + costTypeTextTemp + '币种不正确，请重新选择')
                                //     return
                                // }
                                // if (o.portSurchargeSupply && selecteds[0].portSurchargeSupply && (o.portSurchargeSupply != selecteds[0].portSurchargeSupply)) {
                                //     $.messager.alert('提示', '所选交货单供应商不一致，请重新选择')
                                //     return
                                // }
                                tempLine.costAmount = o.portSurcharge
                                tempLine.costCurreny = o.portSurchargeCurreny
                                tempLine.costSupplyCode = o.portSurchargeSupply
                                tempLine.costSupplyName = o.portSurchargeSupplyName
                                break
                            case 'BXF':
                                if (o.premiumEnd == '1') {
                                    $.messager.alert('提示', '交货单号' + o.orderNo + '的' + costTypeTextTemp + '已生成采购订单，请重新选择')
                                    return
                                }
                                // if (o.premiumCurreny != curreny) {
                                //     $.messager.alert('提示', '所选交货单' + costTypeTextTemp + '币种不正确，请重新选择')
                                //     return
                                // }
                                // if (o.premiumSupply && selecteds[0].premiumSupply && (o.premiumSupply != selecteds[0].premiumSupply)) {
                                //     $.messager.alert('提示', '所选交货单供应商不一致，请重新选择')
                                //     return
                                // }
                                tempLine.costAmount = o.premium
                                tempLine.costCurreny = o.premiumCurreny
                                tempLine.costSupplyCode = o.premiumSupply
                                tempLine.costSupplyName = o.premiumSupplyName
                                break
                            case 'BGF':
                                if (o.customsEnd == '1') {
                                    $.messager.alert('提示', '交货单号' + o.orderNo + '的' + costTypeTextTemp + '已生成采购订单，请重新选择')
                                    return
                                }
                                // if (o.customsCurreny != curreny) {
                                //     $.messager.alert('提示', '所选交货单' + costTypeTextTemp + '币种不正确，请重新选择')
                                //     return
                                // }
                                // if (o.customsSupply && selecteds[0].customsSupply && (o.customsSupply != selecteds[0].customsSupply)) {
                                //     $.messager.alert('提示', '所选交货单供应商不一致，请重新选择')
                                //     return
                                // }
                                tempLine.costAmount = o.customs
                                tempLine.costCurreny = o.customsCurreny
                                tempLine.costSupplyCode = o.customsSupply
                                tempLine.costSupplyName = o.customsSupplyName
                                break
                            case 'BJF':
                                if (o.costomsCensoringChargesEnd == '1') {
                                    $.messager.alert('提示', '交货单号' + o.orderNo + '的' + costTypeTextTemp + '已生成采购订单，请重新选择')
                                    return
                                }
                                // if (o.costomsCensoringChargesCurreny != curreny) {
                                //     $.messager.alert('提示', '所选交货单' + costTypeTextTemp + '币种不正确，请重新选择')
                                //     return
                                // }
                                // if (o.costomsCensoringChargesSupply && selecteds[0].costomsCensoringChargesSupply && (o.costomsCensoringChargesSupply != selecteds[0].costomsCensoringChargesSupply)) {
                                //     $.messager.alert('提示', '所选交货单供应商不一致，请重新选择')
                                //     return
                                // }
                                tempLine.costAmount = o.costomsCensoringCharges
                                tempLine.costCurreny = o.costomsCensoringChargesCurreny
                                tempLine.costSupplyCode = o.costomsCensoringChargesSupply
                                tempLine.costSupplyName = o.costomsCensoringChargesSupplyName
                                break
                            case 'JYF':
                                if (o.surrveyFeesEnd == '1') {
                                    $.messager.alert('提示', '交货单号' + o.orderNo + '的' + costTypeTextTemp + '已生成采购订单，请重新选择')
                                    return
                                }
                                // if (o.surveyFeesCurreny != curreny) {
                                //     $.messager.alert('提示', '所选交货单' + costTypeTextTemp + '币种不正确，请重新选择')
                                //     return
                                // }
                                // if (o.surveyFeesSupply && selecteds[0].surveyFeesSupply && (o.surveyFeesSupply != selecteds[0].surveyFeesSupply)) {
                                //     $.messager.alert('提示', '所选交货单供应商不一致，请重新选择')
                                //     return
                                // }
                                tempLine.costAmount = o.surveyFees
                                tempLine.costCurreny = o.surveyFeesCurreny
                                tempLine.costSupplyCode = o.surveyFeesSupply
                                tempLine.costSupplyName = o.surveyFeesSupplyName
                                break
                        }
                        // 物料编码
                        tempLine.materialCode = o.mmCode
                        // 物料描述
                        tempLine.materialName = o.mmDesc
                        // 签收数量
                        tempLine.signQuantity = o.signQuantity
                        // 销售订单号
                        tempLine.saleOrderNo = o.saleOrderNo
                        // 销售订单行行号
                        tempLine.saleOrderLineNo = o.saleOrderLineNo
                        // 物料组
                        tempLine.materialGropCode = costMmGroupCode
                        tempLine.materialGropDesc = costMmGroupName
                        if (costLinesArr.some((item) => {
                            return item.deliveryNo == o.orderNo
                        })) {
                            $.messager.alert('提示', o.orderNo + '交货单已存在')
                            return
                        } else {
                            $('#costLines').datagrid('appendRow', tempLine)
                        }

                    }
                    $('#selectDeliveryWindow').window('close')
                } else {
                    $.messager.alert('提示', '请选择一条数据')
                    return
                }
            }

            //查询待选交货单列表
            function selectDeliveryList() {
                let startTime = $('#startDeliveryTime').datebox('getValue');
                let endTime = $('#endDeliveryTime').datebox('getValue');
                let curreny = $('#curreny').combobox('getValue');
                let costType = $('#costType').combobox('getValue');
                //  let supplyCode = $('#supplyCode').textbox('getValue');
                // 费用物料组
                let costMmGroupCode = $('#costMmGroupCode').combobox('getValue');
                let deliveryList = $('#deliveryList');
                deliveryList.datagrid('enableFilter');
                deliveryList.datagrid('load', {
                    startTime: startTime ? startTime : '',
                    endTime: endTime ? endTime : '',
                    status: '0',
                    costType: costType ? costType : '',
                    // curreny: curreny ? curreny : '',
                    //   supplyCode: supplyCode ? supplyCode : '',
                    // 费用物料组
                    costMmGroupCode: costMmGroupCode
                })
            }

            // 点击付款货币获取汇率
            function setPayCurrenyExchangeRate(record) {
                // 付款货币
                let tCURR = record.dicValue
                // 约定货币
                let fCURR = $('#curreny').combobox('getValue')
                if (fCURR == tCURR) {
                    $('#rate').numberbox('setValue', 1)
                } else {
                    getDataFormSAP(fCURR, tCURR)
                }

            }

            // 点击约定货币获取汇率
            function setExchangeRate(record) {
                // 付款货币
                let tCURR = $('#payCurreny').combobox('getValue')
                if (!tCURR) {
                    return
                }
                // 约定货币
                let fCURR = record.dicValue
                if (fCURR == tCURR) {
                    $('#rate').numberbox('setValue', 1)
                } else {
                    getDataFormSAP(fCURR, tCURR)
                }

            }

            // 根据参数从sap抓取数据
            function getDataFormSAP(fCURR, TCURR) {
                let paramsZBS4 = {}
                paramsZBS4.ZBS = '4'
                paramsZBS4.FCURR = fCURR
                paramsZBS4.TCURR = TCURR
                paramsZBS4.GDATU = getNowFormatDate()
                if (!paramsZBS4) {
                    $.messager.alert('提示', '请求参数缺失')
                    return
                }
                let result = null;
                $.ajax({
                    type: 'post',
                    url: 'sale/contract/draft/getDataFormSAPByParams',
                    data: JSON.stringify(paramsZBS4),
                    dataType: 'json',
                    contentType: "application/json",
                    async: false,
                    success: function (data) {
                        if (data.code == '60200') {
                            result = data.data
                            $('#rate').numberbox('setValue', JSON.parse(result).UKURS)
                        } else {
                            $.messager.show({
                                title: 'SAP接口回执',
                                msg: '未在SAP系统中查询到汇率,请联系财务部门配置汇率信息',
                                timeout: 3000,
                                showType: 'show'
                            });
                        }
                    }
                })
            }

            // 按钮初始化
            function initBtn(status) {
                if (status == '0') {
                    $('#tabs').tabs({
                        tools: [{
                            text: '保存',
                            iconCls: 'icon-save',
                            handler: function () {
                                save('0');
                            }
                        }, {
                            text: '提交',
                            iconCls: 'icon-ok',
                            handler: function () {
                                $.messager.confirm('提示', '提交后无法再次编辑，确定要提交吗?',
                                    function (r) {
                                        if (r) {
                                            save('1');
                                        }
                                    });
                            }
                        }]
                    })
                    $('#costLines').datagrid({
                        toolbar: [{
                            text: '增加',
                            iconCls: 'icon-add',
                            handler: function () {
                                if (!$('#costType').combobox('getValue')) {
                                    $.messager.alert('提示', '请先选择费用类型')
                                    return
                                }
                                if (!$('#costMmGroupCode').combobox('getValue')) {
                                    $.messager.alert('提示', '请先选择费用物料组')
                                    return
                                }
                                if (!$('#curreny').combobox('getValue')) {
                                    $.messager.alert('提示', '请先选择约定货币')
                                    return
                                }
                                // if (!$('#supplyCode').textbox('getValue')) {
                                //     $.messager.alert('提示', '请先选择供应商')
                                //     return
                                // }
                                selectDeliveryList();
                                $('#selectDeliveryWindow').window('open')
                            }
                        },
                            '-',
                        {
                            text: '删除',
                            iconCls: 'icon-remove',
                            handler: function () {
                                let row = $('#costLines').datagrid('getSelected');
                                if (row) {
                                    let costType = $('#costType').combobox('getValue')
                                    let model = {
                                        deliveryNo: row.deliveryNo,
                                        status: '0',
                                        costType: costType
                                    }
                                    $.messager.confirm('提示', '确定要删除这个吗?', function (r) {
                                        if (r) {
                                            $.ajax({
                                                type: 'post',
                                                dataType: "json",
                                                url: 'purchase/sixCosts/updateDeliveryOrdersStatus',
                                                data: JSON.stringify(model),
                                                success: function (data) {
                                                    // if (data.code != 60200) {
                                                    //     $.messager.alert('消息', data.msg);
                                                    // } else {
                                                    //     $.messager.alert('消息', data.msg);
                                                    //     let dg = $('#dg');
                                                    //     dg.datagrid('enableFilter');
                                                    //     dg.datagrid('load');
                                                    // }
                                                },
                                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                                    // $.messager.alert('消息', errorThrown);
                                                }
                                            })
                                            $('#costLines').datagrid('deleteRow', $('#costLines').datagrid('getRowIndex', row))
                                        }
                                    });
                                } else {
                                    $.messager.alert('消息', '请选中一条数据');
                                }
                            }
                        }]
                    });
                } else {
                    $('#tabs').tabs({
                        tools: null
                    })
                    $('#costLines').datagrid({
                        toolbar: null
                    })
                }
            }

            //编辑
            function editrow(index) {
                if (index >= 0) {
                    $('#dg').datagrid('selectRow', index);
                }
                var row = $('#dg').datagrid('getSelected');
                if (row) {
                    $.ajax({
                        type: 'get',
                        dataType: 'json',
                        url: 'purchase/sixCosts/selectInfor?purId=' + row.purId,
                        success: function (data) {
                            if (data.code != 60200) {
                                $.messager.alert('消息', data.msg);
                            } else {
                                let item = data.data
                                bindCostLinesgrid(item.purchaseSixCostsOrdersLines ? item.purchaseSixCostsOrdersLines : [])
                                initBtn(item.status);
                                //  $('#tabs').tabs('select', 0);
                                $('#add').window('open');
                                $('#tabs').tabs('select', 0)
                                $('#fm').form('load', item);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $.messager.alert('消息', errorThrown);
                        }
                    })
                } else {
                    $.messager.alert('消息', '请选中一条数据');
                    return
                }
            }

            // 保存/提交
            function save(status) {
                if (!$('#fm').form('validate')) {
                    return;
                }
                if (!endEditing()) {
                    $.messager.alert('提示', '费用行项目编辑未结束')
                    return;
                }

                // 税率
                let tax = $('#taxCode').numberbox('getText')
                if (!tax) return
                tax = (Number(tax) / 100)
                console.log('tax==', tax)
                // 汇率
                let rateTep = $('#rate').numberbox('getValue')
                if (!rateTep) return
                const purchaseSixCostsOrdersLines = $('#costLines').datagrid('getRows')
                if (!purchaseSixCostsOrdersLines) {
                    $.messager.alert('提示', '请维护费用行项目')
                    return
                }
                // 供应商赋值
                // 供应商编码
                let baseSupplyCode = $('#supplyCode').textbox('getValue')
                // 判断供应商编码是否相等
                let result = purchaseSixCostsOrdersLines.every((item, index) => {
                    return item.costSupplyCode == baseSupplyCode
                })
                if (!result) {
                    $.messager.alert('提示', '费用供应商不一致，请重新选择')
                    return
                }

                // 订单含税费用
                let orderTaxAmountTem = 0
                // 订单不含税费用
                let orderAmountExTaxTem = 0
                // 税额
                let taxAmount = Number(0)
                // 计算费用(含税费用、不含税费用、税额等)
                for (let i in purchaseSixCostsOrdersLines) {
                    let line = purchaseSixCostsOrdersLines[i]
                    // 计算订单含税总费用
                    orderTaxAmountTem += line.costAmount ? Number(line.costAmount) : 0
                    // 行税额：行费用总额*税率
                    let lineTaxAmount = line.costAmount ? (Number(line.costAmount) / (1 + tax) * tax).toFixed(2) : 0

                    // 行不含税费用:行费用总额-税额
                    line.costExtaxAmount = line.costAmount - lineTaxAmount
                    // 计算总税额
                    taxAmount += Number(lineTaxAmount)
                }
                // 订单含税总费用赋值
                $('#orderAmountTax').numberbox('setValue', orderTaxAmountTem)
                // 订单不含税总费用
                orderAmountExTaxTem = orderTaxAmountTem - taxAmount
                $('#orderAmountExTax').numberbox('setValue', orderAmountExTaxTem.toFixed(2))
                // 税额
                $('#taxAmount').numberbox('setValue', taxAmount)


                let model = {
                    purId: $('#purId').val(),
                    title: $('#title').textbox('getValue'),
                    // sap返回的采购单号
                    sapOrderNo: $('#sapOrderNo').textbox('getValue'),
                    // 需求类型
                    demandType: 'ZB9',
                    // 采购组织
                    purchaseOrg: '1000',
                    // 工厂
                    factoryCode: $('#factoryCode').combobox('getValue'),
                    //公司代码
                    companyCode: $('#companyCode').textbox('getValue'),
                    // 采购组
                    purchaseGroup: PUser.sap,
                    // 供应商编码
                    supplyCode: $('#supplyCode').textbox('getValue'),
                    // 供应商名称
                    supplyName: $('#supplyName').textbox('getValue'),
                    // 付款方式
                    paymentType: $('#paymentType').combobox('getValue'),
                    // 约定币种
                    curreny: $('#curreny').combobox('getValue'),
                    // 费用类型
                    costType: $('#costType').textbox('getValue'),
                    // 采购订单状态
                    status: status,
                    taxCode: $('#taxCode').combobox('getValue'),
                    // 税率
                    tax: $('#taxCode').combobox('getText'),
                    // 费用物料组code
                    costMmGroupCode: $('#costMmGroupCode').combobox('getValue'),
                    // 费用物料组名称
                    costMmGroupName: $('#costMmGroupCode').combobox('getText'),
                    // 付款货币
                    payCurreny: $('#payCurreny').combobox('getValue'),
                    // 汇率
                    rate: $('#rate').numberbox('getValue'),
                    // 订单含税费用赋值
                    orderAmountTax: $('#orderAmountTax').numberbox('getValue'),
                    // 订单不含税费用
                    orderAmountExTax: $('#orderAmountExTax').numberbox('getValue'),
                    // 税额
                    taxAmount: $('#taxAmount').numberbox('getValue', taxAmount),
                    purchaseSixCostsOrdersLines: purchaseSixCostsOrdersLines
                };
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: 'purchase/sixCosts/save',
                    data: JSON.stringify(model),
                    contentType: "application/json",
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', data.msg);
                        } else {
                            var dg = $('#dg');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                            $('#add').window('close');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })

            }

            function del(row) {
                $.ajax({
                    type: 'DELETE',
                    url: 'purchase/sixCosts/delete?purId=' + row.purId,
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', data.msg);
                        } else {
                            $.messager.alert('消息', data.msg);
                            let dg = $('#dg');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })

            }

            // 导出
            function exportList() {
                let startTime = $('#startTime').datebox('getValue')
                let endTime = $('#endTime').datebox('getValue')
                let status = $('#status').combobox('getValue')
                var form = [];
                form.push('startTime=' + (startTime ? startTime : ''));
                form.push('endTime=' + (endTime ? endTime : ''));
                form.push('status=' + (status ? status : ''));
                let url = "purchase / six / costs / orders/export"
                let xhr = new XMLHttpRequest()
                xhr.open('POST', url, true)
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.setRequestHeader('token', localStorage.getItem('token'));
                xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        let blob = this.response
                        let reader = new FileReader()
                        reader.readAsDataURL(blob)
                        reader.onload = function (e) {
                            let a = document.createElement('a')
                            a.download = '询价供应商' + new Date().toLocaleDateString() + '-' + new Date().toLocaleTimeString() + '.xlsx'
                            a.href = e.target.result
                            $('body').append(a)
                            a.click()
                            $(a).remove()
                        }
                    }
                }
                xhr.send(form.join('&'))
            }

            /**
             * 构建待选择的佣金供应商列表window
             */
            function showBrokerageSupplies() {
                $('#selectSupplyWindow').window('open');
            }

            /**
             *构建待选供应商的datagrid
             */
            function setSuppliesDatagird() {
                let supplyDataGrid = $('#supplyDataGrid');
                supplyDataGrid.datagrid({
                    fitColumns: true,
                    url: 'supply/info/selectList',
                    iconCls: 'icon-application',
                    clientPaging: false,
                    checkOnSelect: true,
                    remoteFilter: true,
                    filterDelay: 0,
                    width: 860,
                    height: 300,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: true,
                    pageSize: 6,
                    pageList: [6, 18, 28, 50],
                    remoteSort: true,
                    pagination: true,
                    columns: [
                        [
                            {
                                field: 'ck',
                                checkbox: true,
                                width: 100,
                            },
                            {
                                field: 'infId',
                                title: '供应商id',
                                hidden: true,
                                sortable: true,
                                width: 100,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'infCode',
                                title: '供应商编码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            }, {
                                field: 'infName',
                                title: '名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            }, {
                                field: 'infNameEn',
                                title: '英文名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'infCatagory',
                                title: '供应商类别',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'infType',
                                title: '供应商类型',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'infNature',
                                title: '企业性质',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'infIsInside',
                                title: '内部外部',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'infAdmitLevel',
                                title: '准入级别',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'gramId',
                                title: '方案id',
                                hidden: true,
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'planDeptName',
                                title: '使用单位名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'planIsNeed',
                                title: '是否急用',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createName',
                                title: '制单人名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createTime',
                                title: '创建时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'updateTime',
                                title: '更新时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'status',
                                title: '状态',
                                sortable: true,
                                formatter: function (val, rec) {
                                    let status = val ? val : '';
                                    return unescape(status == '0' ? '待提交' : '已提交');
                                }
                            }
                        ]],
                    toolbar: [{
                        text: '添加',
                        iconCls: 'icon-ok',
                        handler: function () {
                            let suppliesList = $('#supplyDataGrid');
                            const checkedRows = suppliesList.datagrid('getSelected');
                            if (!checkedRows) {
                                $.messager.alert('提示', '请至少选择一条数据');
                                return
                            }
                            if (checkedRows) {
                                $('#supplyName').textbox('setValue', checkedRows.infName)
                                $('#supplyCode').textbox('setValue', checkedRows.infCode)
                            }
                            $('#selectSupplyWindow').window('close');
                        }
                    }]
                })
                supplyDataGrid.datagrid('enableFilter');
            }
        </script>

        </html>